package android.dj.lbscamera.connection;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class LBSCameraService {
	private static final String NET_GOOGLE_LOC_URL = "http://www.google.com/loc/json";
	private static LBSCameraService instance = new LBSCameraService();

	public LBSCameraService() {
		
	}

	public static LBSCameraService getInstance() {
		return instance;
	}

	public String getAddressByLocation(String latitude, String longitude) {
		String result = null;

		try {

			DefaultHttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost(NET_GOOGLE_LOC_URL);
			JSONObject holder = new JSONObject();

			holder.put("version", "1.1.0");
			holder.put("host", "maps.google.com");
			holder.put("request_address", "true");
			holder.put("address_language", "zh_CN");

			JSONObject locationObject = new JSONObject();
			locationObject.put("latitude", latitude);
			locationObject.put("longitude", longitude);

			holder.put("location", locationObject);

			StringEntity se = new StringEntity(holder.toString());
			Log.d("[MASSVIG]", "Location Send = " + holder.toString());
			post.setEntity(se);

			HttpResponse resp = client.execute(post);

			HttpEntity entity = resp.getEntity();

			BufferedReader br = new BufferedReader(new InputStreamReader(
					entity.getContent()));

			StringBuffer sb = new StringBuffer();

			String r = br.readLine();

			while (r != null) {
				Log.d("[MASSVIG]", "Location Receive = " + r);
				sb.append(r);
				r = br.readLine();
			}

			JSONObject data = new JSONObject(sb.toString());
			data = (JSONObject) data.get("location");
			data = (JSONObject) data.get("address");

			result = data.getString("city");
			result += data.getString("street");
//			result += data.getString("street_number");

		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}
	
	public Bitmap getBitmap(String imgUrl) {
		Bitmap bitmap = null;

		try {
			URL url = new URL(imgUrl);

			HttpURLConnection conn = (HttpURLConnection) url.openConnection();

			conn.connect();

			InputStream inputStream = conn.getInputStream();

			bitmap = BitmapFactory.decodeStream(inputStream);

			inputStream.close();

			conn.disconnect();

		} catch (Exception e) {

			e.printStackTrace();
		}

		return bitmap;

	}
}
